<?php

require_once dirname(__FILE__)."/global.php";

header("Access-Control-Allow-Origin: *");

function replaceVars($content)
{
    $content = str_replace('{_IMG_HOST_}', IMG_HOST, $content);
    $content = str_replace('{_STATIC_HOST_}', STATIC_HOST, $content);
    $content = str_replace('{_LOG_HOST_}', LOG_HOST, $content);
    $content = str_replace('{_APITU_HOST_}', APITU_HOST, $content);
    $content = str_replace('{_ENV_}', ENV, $content);
    $content = str_replace('{_KX_COMMON_HOST_}', KX_COMMON_HOST, $content);

    $content = str_replace('{_PIC_WWW_HOST_}', PIC_WWW_HOST, $content);
    return $content;
}

function getHeaders()
{
    if (function_exists('getallheaders'))
    {
        return getallheaders();
    }

    foreach ($_SERVER as $name => $value)
    {
            if (substr($name, 0, 5) == 'HTTP_')
            {
                    $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
            }
    }
    return $headers;
}

function checkCache()
{
    $headers = getHeaders();
    if (isset($headers['If-None-Match'])
        && isset($headers['If-Modified-Since']))
    {
        header("HTTP/1.1 304 Not Modified");
        exit;
    }
}


function mapResource($path)
{
    $delimiter = "/_package/";

    $paths = array();
    if (($pos = strpos($path, $delimiter)) != false)
    {
        $start = $pos + strlen($delimiter);
        $length = 0 - (strlen($path) - strrpos($path, "/"));
        $packageStr = substr($path, $start, $length);
        $paths = explode(",", $packageStr);
    }
    else
    {
        if (preg_match("/(\-[0-9]+[a-z0-9]+)\.(js|css|less)$/", $path, $matches))
        {
            // 带版本号
            $paths[] = str_replace($matches[1], "", $path);
        }
        else
        {
            // 不带版本号
            $paths[] = $path;
        }
    }
    return $paths;
}

function getRealPath($path)
{
    $path = str_replace("..", "", $path);
    return dirname(__FILE__)."/".$path;
}

function outputContentType($extension)
{
    if ($extension == "js")
    {
        header("Content-Type: application/javascript");
    }
    else if ($extension == "css")
    {
        header("Content-Type: text/css");
    }
}

function outputNotFound($resource="")
{
    if (strlen($resource))
    {
        header("X-STATIC: ".$resource." NOT FOUND");
    }
    header("HTTP/1.0 404 Not Found");
}

function renderPackage($resources, $extension)
{
    $payloads = array();
    if ($extension == "js")
    {
        foreach ($resources as $resource)
        {
            $payloads[] = 'if (window.K && K.Resource) {K.Resource.loadJS("http://'.STATIC_HOST.'/'.$resource.'");} else { document.write("<script src=\"http://'.STATIC_HOST.'/'.$resource.'\"></script>");}';
        }
    }
    else if ($extension == "css")
    {
        foreach ($resources as $resource)
        {
            $payloads[] = '@import url("http://'.STATIC_HOST."/".$resource.'");';
        }
    }
    return implode("\n", $payloads);
}

$path = parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
checkCache();

$resources = mapResource($path);
$extension = pathinfo($path, PATHINFO_EXTENSION);

header("Cache-Control: max-age=8640000");
outputContentType($extension);

if (ENV == "development" && count($resources) > 1)
{
    $payload = renderPackage($resources, $extension);
}
else
{
    $payloads = array();
    foreach ($resources as $resource)
    {
        $realPath = getRealPath($resource);
        if (!is_file($realPath))
        {
            outputNotFound($resource);
            exit;
        }

        if ($extension == "js")
        {
            if (defined("HAIBEI_CONVERT") && HAIBEI_CONVERT)
            {
                $cmd = "/usr/local/bin/php ".CORE_ROOT_DIR."/app/haibei/haibei_converter.php ".$realPath;
                $content = `$cmd`;
            }
            else
            {
                $content = file_get_contents($realPath);
            }
        }
        else
        {
            $content = file_get_contents($realPath);
        }
        if ($content)
        {
            $content = replaceVars($content);
            $payloads[] = $content;
        }
    }
    $payload = implode("\n", $payloads);
}

if (strlen($payload))
{
    echo $payload;
}
else
{
    outputNotFound();
}

exit;

?>